<?php

namespace App\Http\Controllers\Front;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\ApiController;
use App\Models\Product;
use App\Models\Shop;
use App\Http\Resources\Front\Product as ProductResource;
use App\Http\Resources\Front\ProductCollection;

class ProductController extends ApiController
{
    /**
     * 商品首页
     */
    public function index(Request $request)
    {
        $cid = $request->input('cid');
        return view('frontdev.product.index', ['cid' => $cid]);
    }

    /**
     * 商品列表
     */
    public function fetchList(Request $request)
    {
        $cid = $request->input('cid');
        $limit = $request->input('size', 10);
        $type = $request->input('type');
        
        $orm = Product::orderBy('id', 'DESC');

        if($type == 'self') {
            // 自营店商品
            $orm->selfSupport();
        } else {
            $orm->normal();
        }

        if($cid) {
            $orm->where('cate_id', $cid);
        }

        $orm->with(['shop' => function($query) {
            $query->select('id', 'name', 'profile', 'address', 'avatar');
        }]);

        return new ProductCollection($orm->paginate($limit));
    }

    /**
     * 获取指定商品信息页面
     */
    public function show($id)
    {
        // 商品详情
        $product =  Product::published()->find($id);

        // 店铺信息
        $shop = Shop::with('user')->find($product->shop_id);

        return view('front.product.show', compact('product', 'shop'));
    }

    /**
     * 获取指定商品信息
     */
    public function fetchDetail($id, Request $request) {
        // 商品详情
        if ($request->input('owner')) {
            // 限定自己的
            $productOrm = Product::Selling()->where('store_id',  $request->user()->id);
        } else {
            $productOrm = Product::Selling()->with(['store']);
        }

        return $this->success($productOrm->find($id));
    }
}
